<?php

namespace App\GraphQL\Mutations\Device;

use App\Models\AgentStatistical;
use App\Models\Device;
use App\Models\DistributorStatistical;
use App\Models\MerchantStatistical;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\DB;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class UnBind
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            
            $id = $args['id'];
            $device = $this->validate($id);
            $oldGroup = $device->group;
            // 代理商设备数统计 减去老的
            $agentStatistical = AgentStatistical::firstOrCreate([
                'user_id' => $oldGroup->user_id
            ]);
            $agentStatistical->decrement('link_device_count');
            // 更新终端伙伴 设备统计
            if ($oldGroup->merchant) {
                $merchantStatistical = MerchantStatistical::firstOrCreate([
                    'user_id' => $oldGroup->merchant->id
                ]);
                $merchantStatistical->decrement('link_device_count');
            }
            // 更新分销商统计
            $distributors = $oldGroup->members()
            ->where('role', 'DISTRIBUTOR')
            ->get();
            $distributors->map(function ($distributor) {
                $distributorStatistical = DistributorStatistical::firstOrCreate([
                    'user_id' => $distributor->user_id
                ]);
                $distributorStatistical->decrement('link_device_count');
            });
            $device->update([
                'status'=>'DORMANT',
                'device_order_id'=>0,
                'device_group_id'=>0
            ]);
        });
        return [
            'status'=> '200',
            'message'=>'更新成功'
        ];
    }
    public function validate($id){
        $old = Device::find($id);
        if (!$old){
            throw new \Exception('设备不存在!');
        }
        return $old;
    }
}
